﻿using AutoMapper;
using MediatR;
using Traceable.App.Application.Command.Aquaculture;
using Traceable.Domian;
using Traceable.ErrorCode;
using Traceable.Infastructure;

namespace Traceable.App.Application.Handler.Aquaculture
{
    public class UpdateAquacultureHandler : IRequestHandler<UpdateAquacultureCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Aquaculture_Table> _aquacultrueRepo;
        private readonly IBaseRepository<Traceable_Table> _traceableRepo;
        private readonly IMapper _mapper;

        public UpdateAquacultureHandler(IBaseRepository<Aquaculture_Table> aquacultrueRepo, IMapper mapper, IBaseRepository<Traceable_Table> traceableRepo)
        {
            _aquacultrueRepo = aquacultrueRepo;
            _mapper = mapper;
            _traceableRepo = traceableRepo;
        }
        /// <summary>
        /// 修改养殖信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(UpdateAquacultureCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int>result = new ApiResult<int>();
            var aquacultrue = _aquacultrueRepo.GetAll().Where(p=>p.Batch_Id==request.Batch_Id && !p.IsDelete).FirstOrDefault();
            
            if (aquacultrue==null)
            {
                var model = _mapper.Map<Aquaculture_Table>(request);
                model.CreateTime=DateTime.Now;
                model.Creater = "张三";
                model.UpdateTime = null;
                var res =_aquacultrueRepo.Add(model);
                if(res>0)
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "添加成功";
                    return Task.FromResult(result);
                }
                else
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "添加失败";
                    return Task.FromResult(result);
                }
                
            }
            else
            {
                aquacultrue =_mapper.Map(request,aquacultrue);
                var res = _aquacultrueRepo.Update(aquacultrue);
                if (res > 0)
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "修改成功";
                    return Task.FromResult(result);
                }
                else
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "修改失败";
                    return Task.FromResult(result);
                }
            }
            
        }
    }
}
